#include "config/type.h"
#include "sched/proc.h"
#include "sys/syscall.h"

// 与进程管理相关的系统调用

// 在 trap.c
extern struct spinlock tickslock;
extern uint ticks;  

// 退出当前进程
uint64 sys_exit(void) {
	int n;
	if (argint(0, &n) < 0) {
	    return -1;
    }
	exit_k(n);
	return 0; 
}

// 取得当前进程号
uint64 sys_getpid(void) { 
	return myproc()->pid; 
}

// 创建新进程
uint64 sys_fork(void) { 
	return fork_k(); 
}

// 等待子进程终止
uint64 sys_wait(void) {
	uint64 p;
	if (argaddr(0, &p) < 0) {
        return -1;
    }
	return wait_k(p);
}

// 增加进程内存空间
uint64 sys_sbrk(void) {
	int addr;
	int n;

	if (argint(0, &n) < 0) {
        return -1;
    }
	addr = myproc()->sz;
	if (growproc(n) < 0) {
        return -1;
    }
	return addr;
}

// 沉睡当前进程
uint64 sys_sleep(void) {
	int n;
	uint ticks0;

	if (argint(0, &n) < 0) {
        return -1;
    }
	acquire(&tickslock);
	ticks0 = ticks;
	while (ticks - ticks0 < n) {
	    if (myproc()->killed) {
	    	release(&tickslock);
	    	return -1;
	    }
	    sleep_k(&ticks, &tickslock);
	}
	release(&tickslock);
	return 0;
}

// 终止进程
uint64 sys_kill(void) {
	int pid;

	if (argint(0, &pid) < 0) {
        return -1;
    }
	return kill_k(pid);
}

// 取得开机以来的时钟中断次数
uint64 sys_uptime(void) {
	uint xticks;

	acquire(&tickslock);
	xticks = ticks;
	release(&tickslock);
	return xticks;
}
